package fi.referencefatory.childphone;

import fi.referencefactory.childphone.R;
import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.graphics.Bitmap;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.TextView;

public class ContactsListAdapter extends ArrayAdapter<ContactItem> {

    // A ViewHolder keeps references to children views to avoid unneccessary calls
    // to findViewById() on each row.
    private class ViewHolder {
    	public ImageView avatar;
    	public TextView name;
    	public TextView number;
    	public CheckBox selected;
    	}
    
    private LayoutInflater mLayoutInflater;
	private ArrayList<ContactItem> mContacts;
	
	public ContactsListAdapter(Context context,
			ArrayList<ContactItem> contacts) {
		super(context, R.layout.contact, contacts);
		// TODO Auto-generated constructor stub
		Log.d("ContactsListAdapter", "ContactsListAdapter");
		mLayoutInflater = LayoutInflater.from(context);
		mContacts = contacts;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
	    // TODO Auto-generated method stub
	    Log.d("ContactsListAdapter", "GetView");
	    
	    ViewHolder holder;
	    
	    View view = convertView;
	    
	    if (view == null) {
	    	view = mLayoutInflater.inflate(R.layout.contact, null);
	    	holder = new ViewHolder();
	    	holder.name = (TextView) view.findViewById(R.id.contact_name);
	    	holder.number = (TextView) view.findViewById(R.id.contact_number);
	    	holder.avatar = (ImageView) view.findViewById(R.id.contact_avatar);
	    	holder.selected = (CheckBox) view.findViewById(R.id.checkBox1);
	    	view.setTag(holder);
	    } else {
	    	holder = (ViewHolder) convertView.getTag();
	    }
	    
	    if (mContacts.size() > position) {
	    	ContactItem obj = mContacts.get(position);
	    	
	    	if (obj != null) {
	    		if (holder.avatar != null) {
	    			if (obj.getAvatarBitmap() != null) {
		    			holder.avatar.setImageBitmap(obj.getAvatarBitmap());
		    		} else {
		    			//holder.avatar.setImageResource(R.drawable.ic_launcher);
		    		}
	    		}
	    		
	    		if (holder.name != null) {
	    			holder.name.setText(obj.getName());
	    		}
	    		
	    		if (holder.number != null) {
	    			holder.number.setText(obj.getNumber());
	    		}
	    		
	    		if (holder.selected != null) {
	    			holder.selected.setChecked(obj.isSelected());
	    		}
	    	}
	    }
	    
	    return view;
	}
	
	@Override
	public int getCount() {
		if (mContacts != null) {
			return mContacts.size();
		} else {
			return 0;
		}
	}
	
	@Override
	public int getPosition(ContactItem item) {
		return mContacts.indexOf(item);

	}
	
	public ContactItem getItem(int position) {
		return mContacts.get(position);
	}
}
